<template>
  <div>
    <a-modal v-if="!(role === 'root')" v-model:open="open" title="Basic Modal" @ok="handleModalOk">
      <p>您确定接收邀请吗</p>
    </a-modal>
    <el-button v-if="role === 'root'" @click="sendPeopleClick">发起邀请</el-button>
    <a-button @click="screenShareClick">开始共享</a-button>
    <div :style="{ background: '#fff', padding: '24px', height: '80%' }">
      <div v-if="role == 'root'">
        <video style="width: 100%; height: 500px;" ref="video" autoplay controls muted />
      </div>
      <div v-else>
        <video style="width: 100%; height: 500px;" ref="video1" autoplay controls muted />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watchEffect, watch } from 'vue';
import { UseSocketStore } from "@/stores/index";
import { useDisplayMedia } from '@vueuse/core';
import { useRouter } from 'vue-router';

let router = useRouter();
const role = router.currentRoute.value.query.role;
const { stream, start } = useDisplayMedia();
const video = ref(null);
const video1 = ref(null)
const store = UseSocketStore();
const roomId = 'WEB-RTC-01';
const open = ref(false);
let peer = ref(null);
let localStream = ref(null);

watch(stream, (newStream, oldStream) => {
  console.log(newStream);
  if (video.value && newStream) {
    video.value.srcObject = newStream;
    store.screenStream = newStream;
  }
});
// 开始直播
watchEffect(() => {
  // 邀请加入直播
  store.socket?.on('callRemote', (msg) => {
    console.log('监听到后端发起请求', msg);
    if (msg) {
      open.value = true;
    }
  });

  // 同意加入直播
  store.socket?.on('acceptCall', async (msg) => {
    console.log('同意加入', msg);

    // other用户同意加入之后 我们要开始创建offer并且传递
    // 创建RTCPeerConnection
    peer.value = new RTCPeerConnection()
    // 添加本地音视频流
    // 替换 addStream 方法为 addTrack 方法
    if (stream.value) {
      stream.value.getTracks().forEach(track => {
        peer.value.addTrack(track, stream.value);
      });
    } else {
      console.error('stream.value is undefined or null');
    }
    // 生成offer
    const offer = await peer.value.createOffer({
      offerToReceiveAudio: 1,
      offerToReceiveVideo: 1
    })
    console.log('本地创建的offer', offer);
    // 设置本地描述的offer
    await peer.value.setLocalDescription(offer);
    // 通过信令服务器将offer发送给用户B
    store.socket?.emit('sendOffer', { offer, roomId })


    peer.value.onicecandidate = (event) => {
      if (event.candidate) {
        console.log('获取本地candidate信息', event.candidate);
        // 通过信令服务器发送candidate信息给发送方
        store.socket?.emit('sendCandidate', {
          roomId,
          candidate: event.candidate
        })
      }
    }
    // 监听onaddstream来获取对方的音视频流
    peer.value.onaddstream = (event) => {
      console.log('------event.stream', event.stream);
      video1.value.srcObject = event.stream;
      if (video1.value) {
        video1.value.srcObject = event.stream;
      }
    }
  });
  store.socket?.on('receiveOffer', async (data) => {
    if (!(role === 'root')) {
      if (!data.offer) return
      console.log('接收到offer', data);
      peer.value = new RTCPeerConnection();

      try {
        // 重置 PeerConnection 状态
        await peer.value.setRemoteDescription(data.offer);
        const answer = await peer.value.createAnswer();
        console.log('本地创建的answer', answer);
        if (!answer) return
        await peer.value.setLocalDescription(answer);
        store.socket?.emit('sendAnswer', { answer, roomId });

        peer.value.onicecandidate = (event) => {
          if (event.candidate) {
            console.log('获取candidate信息', event.candidate);
            store.socket?.emit('sendCandidate', { roomId, candidate: event.candidate });
          }
        };
        // 监听onaddstream来获取对方的音视频流
        // peer.value.onaddstream = (event) => {
        //   console.log('------event.stream', event.stream);
        //   if (video1.value) {
        //     video1.value.srcObject = event.stream;
        //   }
        // }
      } catch (error) {
        console.error('Failed to set remote answer sdp:', error);
      }
    }
  });

  store.socket?.on('receiveAnswer', async (data) => {
    if (role === 'root') {
      console.log('接收到answer', data.answer);
      // 设置远程描述的answer
      // peer.value = new RTCPeerConnection()
      if (data.answer) {
        await peer.value.setRemoteDescription(data.answer);
      }

      peer.value.onicecandidate = (event) => {
        if (event.candidate) {
          console.log('用户B获取candidate信息', event.candidate);
          // 通过信令服务器发送candidate信息给用户A
          socket.value?.emit('sendCandidate', {
            roomId,
            candidate: event.candidate
          })
        }
      }
    }
  })

  store.socket?.on('receiveCandidate', async (data) => {
    console.log('接收到candidate', data.candidate);
    // 设置远程描述的candidate
    await peer.value.addIceCandidate(data.candidate)
  })
});

const sendPeopleClick = async () => {
  console.log('发起视频邀请');
  // 发起视频邀请
  store.socket?.emit('callRemote', roomId);
};

const handleModalOk = async () => {
  open.value = false;
  console.log('同意视频邀请');
  store.socket?.emit('acceptCall', roomId);
};

function screenShareClick() {
  console.log(start);
  start();
}
</script>

<style scoped>
/* 样式 */
</style>
